import axios from "axios";
import Cookies from 'js-cookie'
import {SERVICE_URL} from '@/config' 
import { Message } from "@arco-design/web-react";

export const routes = {
  login: {
    method: "POST",
    url: () => `/api/v1/users/login/access-token`,
  },
  logout: {
    method: "POST",
    url: () => `/api/v1/auth/logout/`,
  },
  register: {
    method: "POST",
    url: () => `/api/v1/users/register`,
  },
  getModels:{
    method: "GET",
    url: () => `/api/v1/llm-models/`,
  },
  getKnowledges:{
    method: "GET",
    url: () => `/api/v1/assistant-categories/`,
  }
}  
export type ILogin = {
  username:string
  password:string
}

export type IRegister = {
  username:string
  password:string
  repassword:string
  full_name:string
  email:string
  phone:string
  id_card:string
  organization:string

}

 class ServiceClient{
  TOKEN:any
  BASEURL:any
  constructor() {
    this.TOKEN = Cookies.get("token") || ''

  }
  async sendRequest(
    method:string,
    url:string,
    data:any = undefined,
    params:any = undefined,
    headerParams = {}
  ) {

    const headers = {
      ...{
        Authorization: `Bearer ${this.TOKEN }`,
        "Content-Type": "application/json",
      },
      ...headerParams
    };
    url = SERVICE_URL+url;
    let response:any={}
    try{
      response = await axios({
          method,
          url,
          ...(method !== "GET" && { data }),
          params,
          headers,
          responseType: "json",
        }); 
    }catch(error:any){
      if(error.status===401 || error.status===409){
        Cookies.remove('token')
        Message.warning("token过期,即将退出！")
        setTimeout(()=>{
          location.reload();
        },2000)
       
      }
      return error.response
    }
      return response;
  }

  login(data:ILogin) {
      return this.sendRequest(
        routes.login.method,
        routes.login.url(),
        data
      );
  }
  logout() {
    return this.sendRequest(
      routes.logout.method,
      routes.logout.url(),
    );
  }
  register(data:IRegister) {
    return this.sendRequest(
      routes.register.method,
      routes.register.url(),
      data
    );
}
  getModels(){
    return this.sendRequest(
      routes.getModels.method,
      routes.getModels.url()
    );
  }
  getKnowledges(){
    return this.sendRequest(
      routes.getKnowledges.method,
      routes.getKnowledges.url()
    );
  };
}

export default ServiceClient

